#include <iostream>
#include <unistd.h>
#include <string>
#include <cerrno>
#include <cstdlib>
#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include "Log.hpp"
#include <string.h>
#include "Inetaddr.hpp"

using namespace std;

enum 
{
    SOCKET_ERROR = 1,
    BIND_ERROR,
    USAGE_ERROR,
};
const static int defaultfd = -1;

class UdpServer
{
public:
    UdpServer(const string& ip, uint16_t port) 
        :_sockfd(defaultfd), _ip(ip), _port(port), _isrunning(false)
    {
    }
    void InitServer()
    {
        //1、创建udpserver套接字
        _sockfd = socket(AF_INET, SOCK_DGRAM, 0);
        if(_sockfd < 0)
        {
            LOG(FATAL, "socket error: , %s, %d\n", strerror(errno), errno);
            exit(SOCKET_ERROR);
        }
        LOG(INFO, "socket create success, sockfd: %d\n", _sockfd);

        //2.0 填充socketadd_in结构(填充字段)
        struct sockaddr_in local;//struct sockadd_in 系统提供的数据类型；local是变量，在栈上开空间
        bzero(&local, sizeof(local));
        local.sin_family = AF_INET;
        local.sin_port = htons(_port);//port经过网络传输给对面，先到网络，_port。主机序列-》网络序列
        local.sin_addr.s_addr = inet_addr(_ip.c_str());//字符串风格的点分十进制的IP地址 -> 4字节IP


        //2.1 bind sockfd和网络消息（IP+port）
        int n = bind(_sockfd, (struct sockaddr*)&local, sizeof(local));
        if(n < 0)
        {
            LOG(FATAL, "bind error: , %s, %d\n", strerror(errno), errno);
            exit(BIND_ERROR);
        }
        LOG(INFO, "socket bind success\n");
    }

    void Start()
    {
        // 服务器都是死循环
        //UDP是面向数据报协议
        _isrunning = true;
        while(true)
        {
            char buffer[1024];
            struct sockaddr_in peer;
            socklen_t len = sizeof(peer);//必须初始化为sizeof(peer)
            //1、让server先收数据
            ssize_t n = recvfrom(_sockfd, buffer, sizeof(buffer)-1, 0, (struct sockaddr*)&peer, &len);
            if(n > 0)
            {
                buffer[n] = 0;
                InetAddr addr(peer);
                LOG(DEBUG, "get message from [%s:%d]: %s\n", addr.Ip().c_str(),addr.Port(), buffer);
                //2、将server收到的消息发送给对方
                sendto(_sockfd, buffer, strlen(buffer), 0, (struct sockaddr*)&peer, len);
            }
            
            
        }
         _isrunning = false;
    }

    ~UdpServer()
    {

    }

private:
    int _sockfd;
    string _ip;
    uint16_t _port;//服务器所用的端口号
    bool _isrunning;//表示服务器是否启动
};
